//
//  DYCAdViewController.m
//  DYCBaisi
//
//  Created by Yachao on 17/6/29.
//  Copyright © 2017年 Yachao. All rights reserved.
//

#import "DYCAdViewController.h"
#import "DYCADItem.h"
#import "DYCTabBarController.h"
/*
 1.广告业务逻辑
 2.占位视图思想:有个控件不确定尺寸,但是层次结构已经确定,就可以使用占位视图思想
 3.屏幕适配.通过屏幕高度判断
 */
@interface DYCAdViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *launchImageView;
//占位视图
@property (weak, nonatomic) IBOutlet UIView *adContainView;

@property (nonatomic, weak) UIImageView *adView;

@property (weak, nonatomic) IBOutlet UIButton *jumpBtn;

@property (nonatomic, strong) DYCADItem *item;

@property (nonatomic, strong) NSTimer *timer;
@end


@implementation DYCAdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // 设置启动图片
    [self setupLaunchImage];
    
    // 加载广告数据 => 拿到活时间 => 服务器 => 查看接口文档 1.判断接口对不对 2.解析数据(w_picurl,ori_curl:跳转到广告界面,w,h) => 请求数据(AFN)
    
    //导入AFN框架：cocodpods
    //cocodpods:管理第三方库，cocodpods做的事情：导入一个框架，会把这个框架依赖的所有框架都导入
    //cocodpods步骤：
    //1.podfile：描述需要导入哪些框架 touch podfile
    //2.打开podfile 描述 open podfile
    //3.搜索需要导入框架描述 pod search
    //4.安装第三方框架 pod install --no-repo-update
    //5.只能用xcworkspace
    
    //Skip running 'pod reop update' before install
    //Podfile.lock :第一次pod 就会自动生成这个文件，描述当前导入框架版本
    //pod install:根据Podfile.lock去加载，第一次会根据podfile文件加载
    //pod update:去查看之前导入框架有没有新的版本，如果有新的版本就会去加载，并且更新pod.lock
    //pod repo:管理第三方仓库的索引，去寻找框架有没有最新版本，有就记录
    [self loadAdData];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
}

- (void)timeChange{
    // 倒计时
    static int i = 3;
    if (i == 0) {
        [self clickJump:nil];
    }
    i--;
    // 设置跳转按钮文字
    [_jumpBtn setTitle:[NSString stringWithFormat:@"跳转 (%d)",i] forState:UIControlStateNormal];
}

// 点击跳转做的事情
- (IBAction)clickJump:(id)sender {
    // 销毁广告界面,进入主框架界面
    DYCTabBarController *tabBar = [[DYCTabBarController alloc] init];
    [UIApplication sharedApplication].keyWindow.rootViewController = tabBar;
    
    // 干掉定时器
    [_timer invalidate];
}

/*
 http://mobads.baidu.com/cpro/ui/mads.php ?=
 */

#pragma mark - 加载广告数据
- (void)loadAdData{

    // unacceptable content-type: text/html"  响应头
    
    // 1.创建请求会话管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.requestSerializer.accept = [NSSet ]
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    // 2.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"code2"] = code2;
    // 3.发送请求
    [manager GET:AdApi parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [responseObject writeToFile:@"/Users/Yachao/Desktop/DYCBaisi/DYCBaisi/Classes/AD(广告)/ad.plist" atomically:YES];
        // 请求数据 -> 解析数据(写成plist文件) -> 设计模型 -> 字典转模型 -> 展示数据
        // 获取字典
        NSDictionary *addDict = [responseObject[@"ad"] lastObject];
        _item = [DYCADItem mj_objectWithKeyValues:addDict];
        CGFloat h = DYCScreenW / _item.w * _item.h;
        // 创建UIImageView展示图片 =>
        self.adView.frame = CGRectMake(0, 0, DYCScreenW, h);
        [self.adView sd_setImageWithURL:[NSURL URLWithString:_item.w_picurl]];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DYCLog(@"%@",error);
    }];
}


// 设置启动图片
- (void)setupLaunchImage
{
    // 6p:LaunchImage-800-Portrait-736h@3x.png
    // 6:LaunchImage-800-667h@2x.png
    // 5:LaunchImage-568h@2x.png
    // 4s:LaunchImage@2x.png
    if (iPhone6P) { // 6p
        self.launchImageView.image = [UIImage imageNamed:@"LaunchImage-800-Portrait-736h"];
    } else if (iPhone6) { // 6
        self.launchImageView.image = [UIImage imageNamed:@"LaunchImage-800-667h"];
    } else if (iPhone5) { // 5
        self.launchImageView.image = [UIImage imageNamed:@"LaunchImage-568h"];
        
    } else if (iPhone4) { // 4
        
        self.launchImageView.image = [UIImage imageNamed:@"LaunchImage-700"];
    }
}

- (UIImageView *)adView{
    if (_adView == nil) {
        UIImageView *imageView = [[UIImageView alloc] init];
        [self.adContainView addSubview:imageView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
        [imageView addGestureRecognizer:tap];
        imageView.userInteractionEnabled = YES;
        _adView = imageView;
    }
    return _adView;
}

// 点击广告界面调用
- (void)tap{
    // 跳转到界面 => safari
    NSURL *url = [NSURL URLWithString:_item.ori_curl];
    UIApplication *app = [UIApplication sharedApplication];
    if ([app canOpenURL:url]) {
        [app openURL:url];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
